package com.briup.bookstore.web.controller;

import com.briup.bookstore.common.model.param.PageParam;
import com.briup.bookstore.common.model.entity.Book;
import com.briup.bookstore.common.model.vo.BookVO;
import com.briup.bookstore.common.response.Result;
import com.briup.bookstore.common.util.PageUtil;
import com.briup.bookstore.service.BookService;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
@RequiredArgsConstructor
public class BookController {

    /**
     * 图书模块Service对象
     */
    private final BookService bookService;

    /**
     * 新增图书信息
     *
     * @param
     * @return
     */
    @PostMapping
    public Result add(@RequestBody Book bookParam) {
        bookService.add(bookParam);
        return Result.ok();
    }

    /**
     * 分页+条件检索图书信息
     *
     * @param pageNum   当前页
     * @param pageSize  每页大小
     * @param keyword   检索关键字（可匹配书名、作者、出版社）
     * @return
     */
    @GetMapping(params = "page=true")
    public Result pageQuery(@RequestParam(value = "pageNum") int pageNum,
                            @RequestParam(value = "pageSize") int pageSize,
                            @RequestParam(value = "keyword", required = false) String keyword,
                            @RequestParam(value = "categoryId", required = false) Integer categoryId) {
        /* 封装分页参数 */
        PageParam pageParam = new PageParam()
                .pageNum(pageNum)
                .pageSize(pageSize);
        /* 封装查询条件参数 */
        Book bookParam = new Book()
                .setKeyword(keyword)
                .setCategoryId(categoryId);
        return Result.ok(PageUtil.convert(bookService.pageQueryByClause(pageParam, bookParam), BookVO::toVO));
    }


    /**
     * 删除图书信息
     * @param ids
     * @return
     */
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable("ids") List<Integer> ids) {
        bookService.delete(ids);
        return Result.ok();
    }


    /**
     * 根据ID查询图书信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable("id") Integer id) {
        return Result.ok(bookService.getById(id));
    }

    /**
     * 修改图书信息
     *
     * @param bookParam
     * @return
     */
    @PutMapping
    public Result update(@RequestBody Book bookParam) {
        bookService.update(bookParam);
        return Result.ok();
    }

    /**
     * 修改图书状态(上架、下架）
     * @return
     */
    @PutMapping(value = "/{id}")
    public Result updateStatus(@PathVariable("id") Integer id,
                               @RequestBody String status) {
        bookService.update(id, Integer.valueOf(status));
        return Result.ok();
    }

}
